package com.carlinfo.userscenter.users.dao.impl;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.carlinfo.userscenter.common.util.DbUtil;
import com.carlinfo.userscenter.users.dao.IARoleDao;
import com.carlinfo.userscenter.users.pojo.ARole;

/**
 * ~角色表操作的Ddao实现类 
 * @author JayLong
 *
 */
public class ARoleDaoImpl implements IARoleDao
{
	/* 加载驱动和获取链接 */
	private DbUtil dbUtil = DbUtil.getInstance();
	
	/**
	 * ~把数据库里面的记录,变成java的对象
	 * ~利用反射 
	 * @param rs
	 * @return
	 * @throws SQLException
	 */
	private ARole convertFormDb(ResultSet rs) throws SQLException
	{
		/*
		 * ~获取Class对象
		 * ~获取所有的method
		 * */
		Class roleCla = ARole.class;
		/* 
		 * new一个对象
		 * ~所有的属性全部是空的,
		 * ~调用set方法
		 *  */
		Object roleObj = null;
		try
		{
			roleObj = roleCla.newInstance();
			
			/* 获取所有的字段 */
			Field[] fields = roleCla.getDeclaredFields();
			for (int i = 0; i < fields.length; i++)
			{
				Field field = fields[i];
				/* 字段名 */
				String name = field.getName();
				//System.out.println(i + "=====" + name);
				/* id=Id */
				String setName = "set" + name.substring(0, 1).toUpperCase() + name.substring(1,name.length());
				System.out.println(i + "=====" + name + "--->" + setName + "----->" + field.getType().getSimpleName());
				Class fieldTypeClass = field.getType();
				/*
				 * set方法
				 * setName
				 * 
				 * ~参数1:指的是方法名;set+属性(首字母大写)
				 * ~参数2:类型;有int,byte,string,Date
				 * */
				Method setMethod = null;
				/*
				 * ~从数据库中取值
				 * POJO中的属性名和表的列名一样,
				 * */
				Object dbObj = null;
				if(fieldTypeClass == int.class || fieldTypeClass == Integer.class)
				{
					setMethod = roleCla.getMethod(setName, int.class);
					dbObj = rs.getInt(name);
				}else if(fieldTypeClass == byte.class || fieldTypeClass == byte.class)
				{
					setMethod = roleCla.getMethod(setName, byte.class);
					dbObj = rs.getByte(name);
				}else if(fieldTypeClass == double.class || fieldTypeClass == double.class)
				{
					setMethod = roleCla.getMethod(setName, double.class);
					dbObj = rs.getDouble(name);
				}else if(fieldTypeClass == String.class )
				{
					setMethod = roleCla.getMethod(setName, String.class);
					dbObj = rs.getString(name);
				}else if(fieldTypeClass == Date.class)
				{
					setMethod = roleCla.getMethod(setName, Date.class);
					dbObj = rs.getTimestamp(name);
				}
				/*
				 * ~执行setMethod
				 * setName(“测试”);的参数是赋值,要从数据库中取
				 * 
				 * ~参数1:是对象,Class对应的对象
				 * ~参数2:方法的形参对应的实参
				 * setName方法可是没有返回值的
				 * */
				setMethod.invoke(roleObj, dbObj);
			}
		} catch (InstantiationException e)
		{
			e.printStackTrace();
		} catch (IllegalAccessException e)
		{
			e.printStackTrace();
		} catch (NoSuchMethodException e)
		{
			e.printStackTrace();
		} catch (SecurityException e)
		{
			e.printStackTrace();
		} catch (IllegalArgumentException e)
		{
			e.printStackTrace();
		} catch (InvocationTargetException e)
		{
			e.printStackTrace();
		}
		return(ARole) roleObj;
	}
	/**
	 * ~把数据库里面的记录,变成java对象
	 * @param rs	数据库需要的结果集
	 * @return	返回当前的对象
	 * @throws SQLException	
	 */
	private ARole convertFormDb_Source(ResultSet rs) throws SQLException
	{
		/* 有结果,把数据库里面的记录,变成java对象 */
		int id = rs.getInt("id");         
		String name = rs.getString("name");    
		String content = rs.getString("content"); 
		byte status = rs.getByte("status");    
		Date createTime = rs.getTimestamp("createTime");
		Date updateTime = rs.getTimestamp("updateTime");
		Date pubTime = rs.getTimestamp("pubTime"); 
		/* getTimestamp getDate getTime */
		System.out.println("id:" + id + ";name:" + name + ";content:" + 
				content + ";status:" + status + ";createTime:" + createTime + ";updateTime:" + updateTime + ";pubTime:" + pubTime);
		ARole role = new ARole();
		role.setId(id);
		role.setName(name);
		role.setContent(content);
		role.setStatus(status);
		role.setCreateTime(createTime);
		role.setUpdateTime(updateTime);
		role.setPubTime(pubTime);
		return role;
	}
	@Override
	public int saveOne(ARole role)
	{
		System.out.println("===ARoleDaoImpl==saveOne==");
		int res = 0 ;
		//添加的sql语句
		String sql = "insert into `a_role`(`name`, `content`, `status`, `createTime`, `updateTime`, `pubTime`)"
				+ " values"
				+ " (?,?,?,?,?,?)";
		//jdbc链接数据库,将对象插入到数据库中 
		//获取链接
		Connection connection = dbUtil.getConnection();
		ResultSet rs = null ;
		try
		{
			//sql语句对象
			PreparedStatement pst = connection.prepareStatement(sql,Statement.RETURN_GENERATED_KEYS);
			/*
			 * ~为占位符赋值
			 * ~参数1:第几个占位符,从1开始 
			 * ~参数2:值 
			 */
			pst.setObject(1, role.getName());
			pst.setObject(2, role.getContent());
			pst.setObject(3, role.getStatus());
			pst.setObject(4, role.getCreateTime());
			pst.setObject(5, role.getUpdateTime());
			pst.setObject(6, role.getPubTime());
			//sql语句影响的条数
			res = pst.executeUpdate();
			
			//获取主键
			rs = pst.getGeneratedKeys();
			//返回的主键,肯定只有一条记录
			if(rs.next())
			{
				//不知道获取主键的sql语句执行 ,主键放到那一列
				int id = rs.getInt(1);
				role.setId(id);
			}
		} catch (SQLException e)
		{
			e.printStackTrace();
		}
		return res;
	}

	@Override
	public int updateOne(ARole role)
	{
		return 0;
	}

	@Override
	public int deleteOne(ARole role)
	{
		return 0;
	}
	
	
	@Override
	public ARole findOne(Map<String, Object> condMap)
	{
		/*-----------拼装sql语句和条件------------- */
		/*
		 * ~存储条件
		 * condMap:用户输入的搜索条件
		 * paramsList:存储的是SQL语句的条件
		 * */
		List<Object> paramsList = new ArrayList<Object>();
		/*
		 * SQL语句和条件
		 * */
		String sql = "select * from a_role";
		/* 根据id查询 */
		if(condMap.get("id")!= null && !"".equalsIgnoreCase(condMap.get("id") + ""))
		{
			/* 您已经传了id */
			sql += " where id = ? ";
			paramsList.add(condMap.get("id"));
		}else if(condMap.get("name")!= null && !"".equalsIgnoreCase(condMap.get("name") + ""))
		{
			/* 根据其他条件查询(名字) */
			sql += " where name = ? ";
			paramsList.add(condMap.get("name"));
		}
		System.out.println("ARole==findOne=sql===" + sql);
		System.out.println("ARole==findOne=条件=== " + paramsList);
		/*---------------标准的JDBC--------------*/
		PreparedStatement ps = null;
		ResultSet rs = null;
		Connection connection = this.dbUtil.getConnection();
		try
		{
			ps = connection.prepareStatement(sql);
			/*
			 * ~设置条件
			 * ~从Map中取值的时候,使用的时候好大方,好气场,一定确定一下有没有放进去
			 * */
			//ps.setObject(1, condMap.get("id"));
			/* 有多少个?就要设置多少个条件 */
			int count = 1;
			for (Iterator iterator = paramsList.iterator(); iterator.hasNext();)
			{
				Object paramObj = (Object) iterator.next();
				ps.setObject(count, paramObj);
				/* 计数器 */
				count ++;
			}
			rs = ps.executeQuery();
			/*
			 * ~如果是多条,使用循环
			 * ~如果是单条,使用判断
			 * */
			if(rs.next())
			{
				/* 将数据库里面的记录变成java对象 */
				ARole role = convertFormDb(rs);
				return role;
			}
		} catch (SQLException e)
		{
			e.printStackTrace();
		}finally
		{
			this.dbUtil.closeAll(connection, ps, rs);
		}
		return null;
	}

	@Override
	public List<ARole> findCondList(Map<String, Object> condMap)
	{
		return null;
	}

}
